package com.sugon.controller.module;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import com.sugon.annotation.AutoLog;
import com.sugon.annotation.DataFilter;
import com.sugon.annotation.NonBusinessParamValid;
import com.sugon.entity.ModuleMaintainPlanEntity;
import com.sugon.entity.ModuleReplacePartEntity;
import com.sugon.modules.base.model.vo.BaseApproveParamVO;
import com.sugon.modules.mold.consts.MoldPmTicketProgressConst;
import com.sugon.modules.mold.consts.MoldReplacePartProgress;
import com.sugon.modules.mold.model.vo.DispatchParamVO;
import com.sugon.modules.mold.service.IMoldMaintenanceManager;
import com.sugon.modules.mold.service.IMoldMaintenanceTicketManager;
import com.sugon.service.ModuleMaintainPlanItemService;
import com.sugon.service.ModuleMaintainPlanService;
import com.sugon.service.ModuleReplacePartService;
import com.sugon.utils.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 模具维护计划Controller
 *
 * @author sugon
 * @date 2019-08-19 09:25:11
 */
@Controller
@RequestMapping("modulemaintainplan")
public class ModuleMaintainPlanController {
    @Autowired
    private ModuleMaintainPlanService moduleMaintainPlanService;
    @Autowired
    private ModuleMaintainPlanItemService moduleMaintainPlanItemService;
    @Autowired
    private IMoldMaintenanceManager moldMaintenanceManager;
    @Autowired
    private ModuleReplacePartService moduleReplacePartService;
    @Autowired
    private IMoldMaintenanceTicketManager moldMaintenanceTicketManager;

    /**
     * 查看列表
     */
    @RequestMapping("/list")
    @DataFilter(deptAlias = "m.DEPT_CODE", userAlias = {"m.CREATE_USER", "m.REPAIR_USER"})
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<ModuleMaintainPlanEntity> moduleMaintainPlanList = moduleMaintainPlanService.queryList(query);
        int total = moduleMaintainPlanService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(moduleMaintainPlanList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看列表
     * 1、维修工查看自己的
     * 2、只查看审核过的工单
     */
    @RequestMapping("/list2")
    @DataFilter(deptAlias = "m.DEPT_CODE", userAlias = {"m.REPAIR_USER", "m.CREATE_USER"})
    @ResponseBody
    public R list2(@RequestParam Map<String, Object> params) {
        com.sugon.utils.MapUtil.removeEmptyValue(params);
        params.put("progressList", CollectionUtil.newArrayList(MoldPmTicketProgressConst.CALL_REPAIR, MoldPmTicketProgressConst.DISPATCH, MoldPmTicketProgressConst.START_REPAIR, MoldPmTicketProgressConst.END_REPAIR, MoldPmTicketProgressConst.CONFIRM, MoldPmTicketProgressConst.CLOSE));
        //查询列表数据
        Query query = new Query(params);
        List<ModuleMaintainPlanEntity> moduleMaintainPlanList = moduleMaintainPlanService.queryList2(query);
        int total = moduleMaintainPlanService.queryTotal2(query);
        PageUtils pageUtil = new PageUtils(moduleMaintainPlanList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    @AutoLog("提交审核-模具维修换件")
    @RequestMapping("/commitApproveReplacePart")
    @RequiresPermissions("modulemaintainplan:commitApproveReplacePart")
    @ResponseBody
    public R commitApproveReplacePart(@RequestParam String id) {
        // 校验是否存在
        ModuleMaintainPlanEntity moldMaintenanceTicket = moduleMaintainPlanService.queryObject(id);
        if (moldMaintenanceTicket == null) {
            return R.error("模具维护工单不存在，请确认!");
        }
        // 校验是否审核中
        int progress = moldMaintenanceTicket.getReplacePartProgress();
        if (progress != MoldReplacePartProgress.NEW && progress != MoldReplacePartProgress.NOT_PASSED) {
            return R.error("模具维护工单审核中或已通过审核，无需重复提交!");
        }
        // 校验是否已填充内容e
        List<ModuleReplacePartEntity> list = moduleReplacePartService.queryList(moldMaintenanceTicket.getMoldId(), 2, moldMaintenanceTicket.getPlanName());
        if (CollectionUtil.isEmpty(list)) {
            return R.error("请在添加换件记录后再提交审核");
        }
        return moldMaintenanceTicketManager.commitApprove(moldMaintenanceTicket) ? R.ok() : R.error("提交失败，请稍后重试!");
    }

    /**
     * 车间授权人审批
     */
    @NonBusinessParamValid
    @AutoLog("车间授权人审批")
    @RequestMapping("/deptCheckReplacePart")
    @RequiresPermissions("modulemaintainplan:deptCheckReplacePart")
    @ResponseBody
    public R deptCheckReplacePart(@Validated @RequestBody BaseApproveParamVO approveParam, BindingResult bindingResult) {
        approveParam.setProcessItem(ProcessInfoEnum.MOLD_REPAIR_RP);
        return moldMaintenanceTicketManager.workshopApprove(approveParam) ? R.ok() : R.error();
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
//    @RequiresPermissions("modulemaintainplan:info")
    @ResponseBody
    public R info(@PathVariable("id") String id) {
        ModuleMaintainPlanEntity moduleMaintainPlan = moduleMaintainPlanService.queryObject(id);

        return R.ok().put("moduleMaintainPlan", moduleMaintainPlan);
    }

    /**
     * 保存
     */
    @AutoLog("模具维护计划--保存")
    @RequestMapping("/save")
    @RequiresPermissions("modulemaintainplan:save")
    @ResponseBody
    public R save(@RequestBody ModuleMaintainPlanEntity moduleMaintainPlan) {
        moduleMaintainPlanService.save(moduleMaintainPlan);

        return R.ok();
    }

    @AutoLog("提交审核-模具定期维护计划")
    @RequestMapping("/commitApprove")
    @RequiresPermissions("modulemaintainplan:save")
    @ResponseBody
    public R commitApprove(@RequestParam String id) {
        // 校验是否存在
        ModuleMaintainPlanEntity moduleMaintainPlan = moduleMaintainPlanService.queryObject(id);
        if (moduleMaintainPlan == null) {
            return R.error("模具定期维护计划不存在，请确认!");
        }
        // 校验是否审核中
        int progress = moduleMaintainPlan.getProgress();
        if (progress != MoldPmTicketProgressConst.NEW && progress != MoldPmTicketProgressConst.NOT_PASSED) {
            return R.error("模具定期维护计划审核中或已通过审核，无需重复提交!");
        }
        // 只可以提交自己编制的需求计划
        if (!moduleMaintainPlan.getCreateUser().equals(ShiroUtils.getUserId())) {
            return R.error("只可以提交自己创建的定期维护计划!");
        }
        // 校验是否已填充内容e
        Map<String, Object> param = MapUtil.newHashMap(1);
        param.put("planID", id);
        Integer itemNum = moduleMaintainPlanItemService.queryTotalByPlan(param);
        if (itemNum <= 0) {
            return R.error("请在添加维护项后再提交审核");
        }
        return moldMaintenanceManager.commitApprove(moduleMaintainPlan) ? R.ok() : R.error("提交失败，请稍后重试!");
    }

    /**
     * 执行计划
     */
    @AutoLog("模具维护计划--执行")
    @RequestMapping("/start")
    @RequiresPermissions("modulemaintainplan:start")
    @ResponseBody
    public R start(@RequestBody ModuleMaintainPlanEntity moduleMaintainPlan) {
        ModuleMaintainPlanEntity moldMaintenanceTicket = moduleMaintainPlanService.queryObject(moduleMaintainPlan.getId());
        if (moldMaintenanceTicket == null) {
            return R.error("工单信息不存在，请确认！");
        }
        // 校验是否处于 待开始状态
        Integer ticketStatus = moldMaintenanceTicket.getProgress();
        if (ticketStatus != MoldPmTicketProgressConst.DISPATCH) {
            return R.error("只可以确认维修处于[待开始]状态的工单！");
        }
        return moldMaintenanceManager.confirmRepair(moldMaintenanceTicket) ? R.ok() : R.error();
    }

    /**
     * 修改
     */
    @AutoLog("模具维护计划--修改")
    @RequestMapping("/update")
    @RequiresPermissions("modulemaintainplan:update")
    @ResponseBody
    public R update(@RequestBody ModuleMaintainPlanEntity moduleMaintainPlan) {
        moduleMaintainPlanService.update(moduleMaintainPlan);

        return R.ok();
    }

    /**
     * 删除
     */
    @AutoLog("模具维护计划--删除")
    @RequestMapping("/delete")
    @RequiresPermissions("modulemaintainplan:delete")
    @ResponseBody
    public R delete(@RequestBody String[] ids) {
        moduleMaintainPlanService.deleteBatch(ids);

        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    @ResponseBody
    public R queryAll(@RequestParam Map<String, Object> params) {

        List<ModuleMaintainPlanEntity> list = moduleMaintainPlanService.queryList(params);
        return R.ok().put("list", list);
    }

    /**
     * 车间授权人审批
     */
    @NonBusinessParamValid
    @AutoLog("车间授权人审批")
    @RequestMapping("/deptCheck")
    @RequiresPermissions("modulemaintainplan:approval")
    @ResponseBody
    public R deptCheck(@Validated @RequestBody BaseApproveParamVO approveParam, BindingResult bindingResult) {
        approveParam.setProcessItem(ProcessInfoEnum.MDE_DQWH);
        return moldMaintenanceManager.workshopApprove(approveParam) ? R.ok() : R.error();
    }

    @NonBusinessParamValid
    @AutoLog("模具维护计划--添加指派人")
    @RequestMapping("/addRepUser")
    @ResponseBody
    public R addRepUser(@Validated @RequestBody DispatchParamVO dispatchParam, BindingResult bindingResult) {
        String id = dispatchParam.getId();
        // 校验是否存在
        ModuleMaintainPlanEntity moduleMaintainPlan = moduleMaintainPlanService.queryObject(id);
        if (moduleMaintainPlan == null) {
            return R.error("模具定期维护计划不存在，请确认！");
        }
        // 校验是否审核中
        int progress = moduleMaintainPlan.getProgress();
        if (progress != MoldPmTicketProgressConst.CALL_REPAIR) {
            return R.error("只可以派工处于[待派工]状态的订单！");
        }
        dispatchParam.setModuleMaintainPlan(moduleMaintainPlan);
        return moldMaintenanceManager.dispatch(dispatchParam) ? R.ok() : R.error();
    }

    /**
     * 获取当前维修人员
     *
     * @return
     */
    @RequestMapping("/repairUser")
    @ResponseBody
    public R repairUser() {
        List list = moduleMaintainPlanService.getFixer();
        return R.ok().put("list", list);
    }

    @RequestMapping("/isOutTime")
    @ResponseBody
    public R isOutTime(String id) {
        int i = moduleMaintainPlanService.isOutTime(id);
        return R.ok().put("res", i);
    }

    //超时申请
    @AutoLog("模具维护计划--超时申请")
    @RequestMapping("/outTime")
    @ResponseBody
    public R outTimeApply(@RequestBody List<String> ids) {
        moduleMaintainPlanService.updateBatch(ids);
        return R.ok();
    }

    /**
     * 流程结束
     */
    @AutoLog("模具维护计划--维护完成")
    @RequestMapping("/endProcess")
    @ResponseBody
    public R endProcess(@RequestBody ModuleMaintainPlanEntity moduleMaintainPlan) {
        ModuleMaintainPlanEntity moduleMaintainPlanInDB = moduleMaintainPlanService.queryObject(moduleMaintainPlan.getId());
        if (moduleMaintainPlanInDB == null) {
            return R.error("模具维护工单不存在，请确认！");
        }
        moduleMaintainPlanInDB.setProgress(MoldPmTicketProgressConst.CONFIRM);
        return moduleMaintainPlanService.endProcess(moduleMaintainPlanInDB) ? R.ok() : R.error();
    }

    /**
     * 流程结束
     */
    @AutoLog("模具维护计划--强制终止计划")
    @RequestMapping("/endProcessPlan")
    @ResponseBody
    public R endProcessPlan(@RequestBody ModuleMaintainPlanEntity moduleMaintainPlan) {
        ModuleMaintainPlanEntity moduleMaintainPlanInDB = moduleMaintainPlanService.queryObject(moduleMaintainPlan.getId());
        if (moduleMaintainPlanInDB == null) {
            return R.error("模具维护工单不存在，请确认！");
        }
        moduleMaintainPlanInDB.setProgress(MoldPmTicketProgressConst.CONFIRM);
        return moduleMaintainPlanService.endProcess(moduleMaintainPlanInDB) ? R.ok() : R.error();
    }

    /**
     * 流程结束
     *
     * @param moduleMaintainPlan
     * @return
     */
    @AutoLog("模具维护计划--效果确认")
    @RequestMapping("/isSure")
    @ResponseBody
    public R isSure(@RequestBody ModuleMaintainPlanEntity moduleMaintainPlan) {
        moduleMaintainPlanService.isSure(moduleMaintainPlan);
        return R.ok();
    }


    /**
     * 流程结束
     *
     * @param params
     * @return
     */
    @AutoLog("模具维护计划--异常添加")
    @RequestMapping("/addError")
    @ResponseBody
    public R addError(@RequestBody Map<String, Object> params) {
        //
        moduleMaintainPlanService.dealError(params);
        return R.ok();
    }

    /**
     * 查询指派人
     *
     * @param id
     * @return
     */
    @RequestMapping("/getAssignUser")
    @ResponseBody
    public R getAssignUser(String id) {
        ModuleMaintainPlanEntity moduleMaintainPlan = moduleMaintainPlanService.queryObject(id);
        return R.ok().put("assign", moduleMaintainPlan.getRepairUser());
    }

    /**
     * 是否添加异常
     *
     * @param id
     * @return
     */
    @RequestMapping("/hasError")
    @ResponseBody
    public R hasError(String id) {
        int i = moduleMaintainPlanService.hasError(id);
        return R.ok().put("hasError", i);
    }
}
